package logic

import (
	"classtype/classtype"
	"classtype/global/model"
	"classtype/internal/svc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassTypeUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassTypeUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassTypeUpdateLogic {
	return &ClassTypeUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassTypeUpdateLogic) ClassTypeUpdate(in *classtype.ClassTypeUpdateRequest) (*classtype.ClassTypeUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var ClassType model.ClassTypes
	if in.Sort < 0 {
		return nil, fmt.Errorf("排序值不可为负")
	}
	if err := model.DB.Where("name = ?", in.Name).Find(&ClassType).Error; err != nil {
		return nil, err
	}
	if ClassType.ID != 0 {
		return nil, fmt.Errorf("目标分类已存在")
	}
	if err := model.DB.Where("id = ?", in.Id).Find(&ClassType).Error; err != nil {
		return nil, err
	}
	if ClassType.ID == 0 {
		return nil, fmt.Errorf("当前分类不可用")
	}
	var CliClass model.ClassTypes
	if err := model.DB.Where("id = ? and parent_id = ?", in.ParentId, ClassType.ID).Find(&CliClass).Error; err != nil {
		return nil, err
	}
	if CliClass.ID != 0 {
		return nil, fmt.Errorf("目标父分类不得为当前子分类")
	}
	if in.Description != "" {
		ClassType.Description = in.Description
	}
	if in.Name != "" {
		ClassType.Name = in.Name
	}
	if in.ParentId >= 0 {
		ClassType.ParentId = int32(in.ParentId)
	}
	if in.Sort >= 0 {
		ClassType.Sort = int32(in.Sort)
	}
	if err := model.DB.Updates(&ClassType).Error; err != nil {
		return nil, err
	}
	model.RDB.Del(model.Ctx, "tree")
	return &classtype.ClassTypeUpdateResponse{}, nil
}
